<!DOCTYPE html>
<html>
    <head>
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1"/>
        <meta charset="UTF-8">
        <meta name="theme-color" content="#4b75ff">
        <link rel="stylesheet" href="../script/semantic/semantic.min.css">
        <script src="../script/jquery.min.js"></script>
        <script src="../script/semantic/semantic.min.js"></script>
        <script src="../script/ao_module.js"></script>
        <script src="script/DPlayer.min.js"></script>

        <link rel="manifest" crossorigin="use-credentials" href="manifest.json">
        <title>Video</title>
        <style>
            html, body{
                background-color:rgba(250,250,250,0.95);
                padding:0px !important;
                margin: 0px;
            }
            #dplayer{
                display:inline-block;
                width:70%;
                vertical-align: top;
            }
            .playerwrapper{
                background-color:black;
                width:100%;
                margin-bottom:12px;
            }

            @media only screen and (max-width: 1900px) {
                #dplayer{
                    width:50%;
                }
            }

            @media only screen and (max-width: 1500px) {
                #dplayer{
                    width:60%;
                }
            }

            @media only screen and (max-width: 1024px) {
                #dplayer{
                    width:70%;
                }
            }

            @media only screen and (max-width: 600px) {
                #dplayer{
                    width:100%;
                }
            }
            .playing{
                background-color:#ededed;
            }

            .videoObject{
                padding:6px !important; 
                cursor: pointer;
            }

            .videoObject:hover{
                background-color: #ffdd91;
            }

            .playlistObject{
                padding: 0.8em !important;
                cursor: pointer;
            }

            .playlistObject:hover{
                background-color: #ffdd91;
            }

            .playlistObject.active{
                background-color:#ededed;
            }

        </style>
    </head>
    <body>
        <!-- Viewing Panel-->
        <div class="playerwrapper" align="center">
            <div id="dplayer" class="unstyled" align="left"></div>
        </div>
        <!-- PlayList-->
        <div class="ui container">
            <h3 class="ui header">
                <span id="videoname">No Video Loaded</span>
                <div class="sub header"><span id="playlistName">N/A</span> / <span id="ext">[no_media]</span></div>
            </h3>
            <div class="ui segment">
                <p><i class="expand icon"></i>Screen Size</p>
                <!--
                    <button class="ui tiny button" onclick="setScreenSize('50%');">
                        Small
                    </button>
                 -->
                <button class="ui tiny button" onclick="setScreenSize('70%'); previousScreenSize='70%';">
                    Normal
                </button>
                <button class="ui tiny button" onclick="setScreenSize('100%');previousScreenSize='100%';">
                    Full Width
                </button>
                <div class="ui toggle right floated checkbox">
                    <input id="autoplayToggle" type="checkbox" name="autoplay" onchange="setAutoplay(this);">
                    <label>Autoplay</label>
                </div>
            </div>
            
            <div class="ui fluid segment">
                <div class="ui icon tiny right floated basic buttons">
                    <button onclick="playPreviousVideo();" class="ui tiny basic icon button"><i class="step backward icon"></i></button>
                    <button onclick="jumpToPlayingPlaylist();" class="ui tiny basic icon button"><i class="list icon"></i></button>
                    <button onclick="jumpToPlayingVideo();" class="ui tiny basic icon button"><i class="arrow down icon"></i></button>
                    <button onclick="playNextVideo();" class="ui tiny basic icon button"><i class="step forward icon"></i></button>
                </div>
                <div id="playList" class="ui accordion">
                    <div class="title">
                        <i class="dropdown icon"></i>
                        <i class="list icon"></i> PlayLists
                    </div>
                    <div class="content">
                        <div id="playListSelector" class="ui relaxed divided list">
                            
                        </div>
                    </div>
                    
                    <div class="title">
                        <i class="dropdown icon"></i>
                        <i class="file icon"></i>PlayList Videos
                    </div>
                    <div class="content">
                        <div id="videolist" class="ui relaxed divided list">

                        </div>
                    </div>
                </div>
            </div>
            <br><br><br>
        </div>
        
        <script>
            var playerObject;
            var AllPlaylist = [];
            var currentPlaylist = [];
            var currentPlaying;
            //var unsortedVideoFiles = [];
            var autoPlay = false;
            var previousScreenSize = "70%";
            $('.ui.dropdown').dropdown();
            
            init();
            initPlaylist();

            //Check if there are file dropped into this interface. If yes, redirect to embedded
            var infile = ao_module_loadInputFiles();
            if (infile != null){
                window.location.href = "embedded.html" + window.location.hash;
            }

            autoPlay = (ao_module_storage.loadStorage("Video","autoplay") == "true");
            if (autoPlay){
                $("#autoplayToggle").attr("checked",true);
            }

            function init(){
                //Removed set global volume and isolate two systems
                /*var defaultVol = localStorage.getItem("global_volume");
                if (defaultVol == null || defaultVol == "" || defaultVol == undefined){
                    defaultVol = 0.4;
                }
                */
                const dp = new DPlayer({
                    container: document.getElementById('dplayer'),
                    autoplay: false,
                    //volume: parseFloat(defaultVol),
                    video: {
                        pic: 'img/thumbnail.png',
                    }
                });

                playerObject = dp;

                /*
                dp.on("volumechange",function(){
                    var newVol = dp.volume();
                    if (localStorage){
                        localStorage.setItem("global_volume",newVol);
                    }
                });
                */
                
                //handle autoplay on end
                dp.on('ended', function() {
                    if (autoPlay){
                        //Play next item in list
                        playNextVideo();
                    }
                });


                //Handle full screen
                dp.on('fullscreen', function() {
                    //previousScreenSize = $("#dplayer").css("width");
                    setScreenSize("100%");
                });

                dp.on('fullscreen_cancel', function() {
                    setScreenSize(previousScreenSize);
                });

            }

            function playNextVideo(){
                var nextToPlay = 0;
                for (var i =0; i < currentPlaylist.length; i++){
                    if (currentPlaylist[i].Filename == currentPlaying){
                        nextToPlay = i + 1;
                        if (nextToPlay >= currentPlaylist.length){
                            //last video. loop back to first esp
                            nextToPlay = 0;
                        }
                    }
                }

                //Play the selected item
                var nextPlayObject = currentPlaylist[nextToPlay];
                if (nextPlayObject  == undefined){
                    //No playlist or no object to play
                    return;
                }
                console.log(currentPlaylist[nextToPlay],nextToPlay);
                $("#videoname").text(nextPlayObject.Filename);
                $("#ext").text("[" + nextPlayObject.Ext + "]" );
                currentPlaying = nextPlayObject.Filename;
                playVideo("../media?file=" + encodeURIComponent(nextPlayObject.Filepath));
                $("#videolist").find(".search").val(nextPlayObject.Filename);
                $(".playing").removeClass("playing");
                $(".videoObject").each(function(){
                    if ($(this).attr("filename") + $(this).attr("ext") == nextPlayObject.Filename){
                        $(this).addClass("playing");
                    }
                });
            }

            function playPreviousVideo(){
                var nextToPlay = 0;
                for (var i =0; i < currentPlaylist.length; i++){
                    if (currentPlaylist[i].Filename == currentPlaying){
                        nextToPlay = i - 1;
                        if (nextToPlay < 0){
                            //First video. Loopback to the final video
                            nextToPlay = currentPlaylist.length - 1;
                        }
                    }
                }

                //Play the selected item
                var nextPlayObject = currentPlaylist[nextToPlay];
                if (nextPlayObject  == undefined){
                    //No playlist or no object to play
                    return;
                }
                console.log(currentPlaylist[nextToPlay],nextToPlay);
                $("#videoname").text(nextPlayObject.Filename);
                $("#ext").text("[" + nextPlayObject.Ext + "]" );
                currentPlaying = nextPlayObject.Filename;
                playVideo("../media?file=" + encodeURIComponent(nextPlayObject.Filepath));
                $("#videolist").find(".search").val(nextPlayObject.Filename);
                $(".playing").removeClass("playing");
                $(".videoObject").each(function(){
                    if ($(this).attr("filename") + $(this).attr("ext") == nextPlayObject.Filename){
                        $(this).addClass("playing");
                    }
                });
            }

            function jumpToPlayingVideo(){
                if ($(".videoObject.playing").length == 0){
                    return;
                }
                var scrollToLocation = $(".videoObject.playing").offset().top;
                $('html, body').animate({
                    scrollTop: scrollToLocation
                }, 200);
            }

            function jumpToPlayingPlaylist(){
                if ($(".playlistObject.active").length == 0){
                    return;
                }
                var scrollToLocation = $(".playlistObject.active").offset().top;
                $('html, body').animate({
                    scrollTop: scrollToLocation
                }, 200);
            }

            function setAutoplay(obj){
                autoPlay = obj.checked;
                if (autoPlay){
                    ao_module_storage.setStorage("Video","autoplay","true");
                }else{
                    ao_module_storage.setStorage("Video","autoplay","false");
                }
            }

            /*
            $("#playListSelector").on("change",function(){
                var selectedPlaylistName = $(this).val();
                var thisPlaylistDevice = "";
                $("#playListSelector").find(".playlistObject").each(function(){
                    if ($(this).attr("value") == selectedPlaylistName){
                        thisPlaylistDevice = $(this).attr("device");
                    }
                });

                if (thisPlaylistDevice.length == 0){
                    //Unsorted playlist
                    console.log("Listing unsorted playlists");
                    listUnsortedFiles();
                }else{
                    listPlayList(selectedPlaylistName);
                }
                //console.log(thisPlaylistDevice);
            });
            */

            function selectedPlaylist(object, selectedPlaylistName){
                //Hightlight this playlist object
                $(".playlistObject.active").removeClass('active');
                $(object).addClass("active");
                listPlayList(selectedPlaylistName);
                $('#playList').accordion('open',1);
            }

            function setScreenSize(size){
                $("#dplayer").css("width",size);
            }   

            function initPlaylist(){
                $.ajax({
                    url: "../system/ajgi/interface?script=Video/backend/buildPlaylist.js",
                    success: function(data){
                        console.log(data);
                        //Initial playlist dropdown
                        $("#playListSelector").html("");
                        //$("#playListSelector").append(`<option class="" value="">Select Playlist</option>`);
                       for (var i = 0; i < data.length; i++){
                           var thisDevice = data[i];
                           var thisDeviceName = thisDevice.StorageName;
                           var playlistInThisDevice = thisDevice.PlayLists;
                          
                           //var unsortedVideoInThisDevice = thisDevice.UnsortedVideos;
                           //Append playlist
                           for (var j = 0; j < playlistInThisDevice.length; j++){
                                var thisPlaylistName = playlistInThisDevice[j].Name;
                                var thisPlaylistThumbnail = playlistInThisDevice[j].Thumbnail;
                                if (thisPlaylistThumbnail == false){
                                    thisPlaylistThumbnail = "img/desktop_icon.png";
                                }else{
                                    thisPlaylistThumbnail = "data:image/jpg;base64," + thisPlaylistThumbnail;
                                }
                                AllPlaylist.push(JSON.parse(JSON.stringify(playlistInThisDevice[j])));
                                //$("#playListSelector").append(`<option class="playlistObject" value="${thisPlaylistName}" device="${thisDeviceName}">${thisPlaylistName}</option>`);
                                $("#playListSelector").append(`
                                    <div class="playlistObject item" onclick="selectedPlaylist(this,'${thisPlaylistName}');">
                                        <div class="right floated content">
                                            <div onclick="event.preventDefault(); event.stopImmediatePropagation(); ao_module_openPath('${playlistInThisDevice[j].Folderpath}');" class="ui icon button"><i class="folder open icon"></i></div>
                                        </div>
                                        <img class="ui tiny image " src="${thisPlaylistThumbnail}">
                                        <div class="content" style="margin-top: 1em; max-width: calc(100% - 15em);">
                                            <div class="header">${thisPlaylistName}</div>
                                            <div class="description" style="margin-top: 0.4em;" ><span style="margin-left: 0em;"><i class="file outline icon"></i> x  ${playlistInThisDevice[j].Files.length}</span></div>
                                        </div>
                                    </div>
                                `);
                           }
                           /*
                           for (var k = 0; k < unsortedVideoInThisDevice.length; k++){
                                unsortedVideoFiles.push(JSON.parse(JSON.stringify(unsortedVideoInThisDevice[k])));
                           }
                           */
                           
                       }
                        //Append unsorted into playlist
                        //$("#playListSelector").append(`<option class="playlistObject" value="unsorted" device="">Unsorted Playlist</option>`);
                        updateWindowEvents();
                        $("#playList").accordion();
                        $('#playList').accordion('open',0);
                    }
                });
            }

            function listPlayList(playlistName){
                $("#videolist").html("");
                var targetPlaylist;
                for (var i =0; i < AllPlaylist.length; i++){
                    if (AllPlaylist[i].Name == playlistName){
                        targetPlaylist = AllPlaylist[i];
                    }
                }
                currentPlaylist = targetPlaylist.Files;
                //Parse the playlist
                for (var i = 0; i < currentPlaylist.length; i++){
                    var playListName = targetPlaylist.Name;
                    var thisVideoName = currentPlaylist[i].Filename;
                    thisVideoName = thisVideoName.split(".");
                    thisVideoName.pop();
                    thisVideoName = thisVideoName.join(".");
                    var thisFilePath = currentPlaylist[i].Filepath;
                    var ext = currentPlaylist[i].Ext;
                    $("#videolist").append(`<div class="item videoObject" onclick="playThisFile(this);" filename="${thisVideoName}" filepath="${thisFilePath}" ext="${ext}" playlist="${playListName}">
                        <img class="ui top aligned tiny image thumbnail" src="img/no_preview.svg">
                        <div class="content" style="width: calc(100% - 100px);">
                            <p class="header">${thisVideoName}</p>
                            <div class="description">${thisFilePath} <br> ${ext.substr(1)}</div>
                        </div>
                    </div>`);
                }

                //Render the thumbnail
                $(".videoObject").each(function(){
                    let vidDomElet = $(this);
                    ao_module_agirun("Video/backend/getThumbnail.js", {
                        file: $(this).attr("filepath")
                    },function(data){
                        if (data.error == undefined && data.length > 0){
                            //Thumbnail get. Render it to the DOM element
                            $(vidDomElet).find(".thumbnail").attr("src", 'data:image/jpg;base64,' + data);
                        }
                    } );
                });

            }

            function playThisFile(obj){
                $(".playing").removeClass("playing");
                //var fileDescriptor = $(obj).parent().parent();
                var fileDescriptor = $(obj);
                $("#videoname").text(fileDescriptor.attr("filename"));
                $("#playlistName").text(fileDescriptor.attr("playlist"));
                $("#ext").text("[" + fileDescriptor.attr("ext") + "]" );
                currentPlaying = fileDescriptor.attr('filename') + fileDescriptor.attr("ext");
                playVideo("../media?file=" + encodeURIComponent(fileDescriptor.attr("filepath")));
                $(fileDescriptor).addClass("playing");
                window.scrollTo(0, 0); 
                ao_module_setWindowTitle("Video - " + fileDescriptor.attr("filename"));
            }

            function playVideo(src){
                playerObject.video.src = src;
                playerObject.play()
                updateWindowEvents();
            }
            
            $(window).on("resize",function(){
                updateWindowEvents();
            });

            function updateWindowEvents(){
                $("#dplayer").css("max-height",window.innerHeight);
            }
        </script>
    </body>
</html>